{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf \n",
    "import matplotlib.pyplot as plt \n",
    "\n",
    "# import input_data\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "from tensorflow.examples.tutorials.mnist import input_data "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting data/train-images-idx3-ubyte.gz\n",
      "Extracting data/train-labels-idx1-ubyte.gz\n",
      "Extracting data/t10k-images-idx3-ubyte.gz\n",
      "Extracting data/t10k-labels-idx1-ubyte.gz\n",
      "done\n"
     ]
    }
   ],
   "source": [
    "mnist = input_data.read_data_sets('data/',one_hot=True)\n",
    "print ('done')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainimgs = mnist.train.images\n",
    "trainlabels = mnist.train.labels\n",
    "testimgs = mnist.test.images\n",
    "testlabels = mnist.test.labels\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[28600 45268 41606 52883 30046]\n"
     ]
    }
   ],
   "source": [
    "num_samples = 5\n",
    "randidx = np.random.randint(trainimgs.shape[0],size=num_samples)\n",
    "print(randidx)\n",
    "\n",
    "for i in randidx:\n",
    "    cur_img = np.reshape(trainimgs[i,:],(28,28))\n",
    "    cur_labl = np.argmax(trainlabels[i,:])\n",
    "    plt.matshow(cur_img,cmap = plt.get_cmap('gray'))\n",
    "    plt.title(str(i)+\"th training img,\"+\"label is : \"+str(cur_labl))\n",
    "#     print(str(i)+\"th training img,\"+\"label is : \"+\"str(cur_labl)\")\n",
    "#     plt.show()\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x = tf.placeholder('float',[None,784])\n",
    "y = tf.placeholder('float',[None,10])\n",
    "W = tf.Variable(tf.random_uniform((784,10),minval=0.0,maxval=0.5,dtype=tf.float32))\n",
    "b = tf.Variable(tf.zeros([10]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 逻辑回归model\n",
    "# softmax score\n",
    "score = tf.nn.softmax(tf.matmul(x,W)+b)\n",
    "sum_log_per_row = -tf.reduce_sum(y*tf.log(score),reduction_indices=1)\n",
    "loss = tf.reduce_mean(sum_log_per_row)\n",
    "optm = tf.train.GradientDescentOptimizer(0.001).minimize(loss)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "# tf.arg_max( input, dimension, output_type=tf.int64,  name=None )\n",
    "pred = tf.equal(tf.arg_max(score,1),tf.arg_max(y,1))\n",
    "# accuracy calculate 转换为float型再算百分比\n",
    "acc = tf.reduce_mean(tf.cast(pred,'float'))\n",
    "\n",
    "# 初始化\n",
    "init = tf.global_variables_initializer()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch:000/050 loss:0.005252953 train_acc: 0.160 test_acc: 0.130\n",
      "epoch:005/050 loss:0.004682938 train_acc: 0.170 test_acc: 0.132\n",
      "epoch:010/050 loss:0.004825162 train_acc: 0.130 test_acc: 0.133\n",
      "epoch:015/050 loss:0.005415515 train_acc: 0.100 test_acc: 0.134\n",
      "epoch:020/050 loss:0.004894531 train_acc: 0.160 test_acc: 0.135\n",
      "epoch:025/050 loss:0.005152711 train_acc: 0.140 test_acc: 0.137\n",
      "epoch:030/050 loss:0.004765899 train_acc: 0.190 test_acc: 0.138\n",
      "epoch:035/050 loss:0.005143068 train_acc: 0.110 test_acc: 0.140\n",
      "epoch:040/050 loss:0.004881804 train_acc: 0.070 test_acc: 0.141\n",
      "epoch:045/050 loss:0.004816141 train_acc: 0.200 test_acc: 0.142\n",
      "finish\n"
     ]
    }
   ],
   "source": [
    "epochs = 50\n",
    "batch_size = 100\n",
    "display_step = 5\n",
    "\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    \n",
    "    for epoch in range(epochs):\n",
    "        avg_loss = 0\n",
    "        num_batch = int(mnist.train.num_examples/batch_size)\n",
    "        batch_xs,batch_ys = mnist.train.next_batch(batch_size)\n",
    "        feeds = {x:batch_xs,y:batch_ys}\n",
    "        \n",
    "        sess.run(optm,feed_dict=feeds)\n",
    "        avg_loss += sess.run(loss,feed_dict=feeds)/num_batch\n",
    "        \n",
    "        # display\n",
    "        if epoch%display_step == 0:\n",
    "            feeds_train = {x:batch_xs,y:batch_ys}\n",
    "            feed_test = {x:mnist.test.images,y:mnist.test.labels}\n",
    "            train_acc = sess.run(acc,feed_dict=feeds_train)\n",
    "            test_acc = sess.run(acc,feed_test)\n",
    "            print ('epoch:%03d/%03d loss:%.9f train_acc: %.3f test_acc: %.3f'\n",
    "                  %(epoch,epochs,avg_loss,train_acc,test_acc))\n",
    "    print('finish')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
